import React, { useState } from "react";
import { Input, Select } from 'antd';

function createTextField(value: any, handleChange: any) {
    return (<Input value={value} onChange={handleChange} />)
}

function createTextAreaField(value: any, handleChange: any) {
    return (<Input.TextArea value={value} onChange={handleChange} />)
}

function createSelectField(value: any, handleChange: any, item: any) {
    const { options } = item;
    return (<Select style={{ width: 100 }} placeholder="请选择" value={value} onChange={handleChange}>
                {
                    options.map((it, index: number) => (
                        <Select.Option key={index} value={it.value}>{it.label}</Select.Option>
                    ))
                }
            </Select>)
}

function FormFiled(props: any) {
    const { name, form } = props
    const [innerValue, setInnerValue] = useState('')
    const type = form.getFieldType(name);
    const item = form.getField(name);

    let fieldElement: any = null

    function handleChange(e: any) {
        const val = typeof e === 'object' ? e.target.value : e;
        setInnerValue(val)
        form.dispatchValue({
            name, value: val
        });
        form.validateFields(name)
    }

    switch (type) {
        case 'TEXT': {
            fieldElement = createTextField(innerValue, handleChange)
            break
        }
        case 'TEXTAREA': {
            fieldElement = createTextAreaField(innerValue, handleChange)
            break
        }
        case 'SELECT': {
            fieldElement = createSelectField(innerValue, handleChange, item)
            break
        }
    }

    return (<div>
        {fieldElement}
    </div>)
}

export default FormFiled